package com.gitee.dupe.oauth.granter;

import cn.hutool.core.util.StrUtil;
import com.gitee.dolt.core.constant.RoleConstant;
import com.gitee.dolt.security.model.AuthInfo;
import com.gitee.dolt.security.model.SysUser;
import com.gitee.dolt.security.token.TokenProvider;
import com.gitee.dolt.utils.StrUtils;
import com.gitee.dupe.authority.dto.MenuDTO;
import com.gitee.dupe.authority.entity.Resource;
import com.gitee.dupe.authority.entity.User;
import com.gitee.dupe.authority.enumeration.ResourceTypeEnum;
import com.gitee.dupe.authority.service.IResourceService;
import com.gitee.dupe.authority.service.IRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 验证码TokenGranter
 *
 * @author LYH
 */
@Slf4j
@RequiredArgsConstructor
public abstract class AbstractTokenGranter implements TokenGranter {

    protected final TokenProvider tokenProvider;
    protected final IRoleService roleService;
    protected final IResourceService resourceService;

    protected AuthInfo createAuthInfo(User user) {
        Long userId = user.getId();
        List<String> roles = new ArrayList<>();
        List<String> resources;
        roleService.findAllEnabledByUserId(userId).forEach(e -> {
            roles.add(e.getRoleIdent());
        });
        if (roles.contains(RoleConstant.SUPER_ADMIN)) {
            // 超管给所有权限
            resources = Arrays.asList("*");
        } else {
            List<Resource> userResources = resourceService.findAllEnabledByUserId(userId);
            resources = userResources.stream().map(Resource::getIdent)
                    .filter(StrUtil::isNotEmpty).flatMap(e -> Arrays.stream(StrUtil.split(e, StrUtils.SEMICOLON)))
                    .collect(Collectors.toList());
        }
        SysUser sysUser = new SysUser().setId(user.getId()).setAccount(user.getAccount()).setName(user.getRealName())
                .setScope(user.getGroup()).setRoles(roles).setResources(resources);
        return tokenProvider.createAuthInfo(sysUser);
    }


}
